package com.chatSystem;

import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Client {
    public static void main(String[] args) {
        new Login();
    }
}


class ClientReadAndPrint extends Thread{
    static Socket mySocket = null;
    static JTextField textInput;
    static JTextArea textShow;
    static JFrame chatViewJFrame;
    static BufferedReader bufferedReader = null;
    static PrintWriter out = null;
    static String userName;
    JButton send = ChatView.getSend();
    JButton xuan = ChatView.getXuan();
    JButton tao = ChatView.getTao();
    JButton yuan = ChatView.getYuan();


    //接收类
    public void run(){
//        int showXuan = 0;
//        int showTao = 0;
//        int showYuan = 0;
        try{
            bufferedReader = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            xuan.setEnabled(false);
            tao.setEnabled(false);
            yuan.setEnabled(false);
            if(Server.haveUser[0] == 1){
                xuan.setEnabled(true);
            }
            if(Server.haveUser[1] == 1){
                tao.setEnabled(true);
            }
            if(Server.haveUser[2] == 1){
                yuan.setEnabled(true);
            }

            while(true){
                String str = bufferedReader.readLine();
//                if(str.contains("好友[xuan]已上线") || str.contains("好友[tao]已上线")||
//                        str.contains("好友[yuan]已上线") || str.contains("好友[xuan]已下线") || str.contains("好友[tao]已上线")
//                        || str.contains("好友[yuan]已下线")){}

                if(str.contains("好友[xuan]已上线")){
                    xuan.setEnabled(true);
                    str = "";
                }
                if(str.contains("好友[tao]已上线")){
                    tao.setEnabled(true);
                    str = "";
                }
                if(str.contains("好友[yuan]已上线")){
                    yuan.setEnabled(true);
                    str = "";
                }
                if(str.contains("好友[xuan]已下线")){
                    xuan.setEnabled(false);
                    str = "";
                }
                if(str.contains("好友[tao]已下线")){
                    tao.setEnabled(false);
                    str = "";
                }
                if(str.contains("好友[yuan]已下线")){
                    yuan.setEnabled(false);
                    str = "";
                }
                if(str.contains(userName)) {
                    String name = userName;
                    String appendStr = str.replace("@"+name,"");
                    textShow.append(appendStr + "\n");
                    textShow.setCaretPosition(textShow.getDocument().getLength());
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(str.contains("服务器消息:您已被下线，消息将不会再被递送到其他客户端@" + userName)){
                    textShow.append(simpleDateFormat.format(new Date()) + "服务器消息:您已被下线，消息将不会再被递送到其他客户端" + '\n');
                    out.println(simpleDateFormat.format(new Date()) + "用户[" + userName + "]已从服务器断开");
                    out.flush();
                    bufferedReader.close();
                    out.close();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /*--------------登录监听---------------*/
    class LoginListen implements ActionListener{
        JTextField textField;
        JPasswordField pwdField;
        JFrame loginJFrame;//登录窗口本身
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ChatView chatView = null;

        public void setJTextField(JTextField textField) {
            this.textField = textField;
        }
        public void setJPasswordField(JPasswordField pwdField) {
            this.pwdField = pwdField;
        }
        public void setJFrame(JFrame jFrame) {
            this.loginJFrame = jFrame;
        }
        public void actionPerformed(ActionEvent evnet){
            userName = textField.getText();
            String userPwd = String.valueOf(pwdField.getPassword());
            if((userName.equals("xuan") && userPwd.equals("123"))||(userName.equals("tao") && userPwd.equals("123"))||(userName.equals("yuan") && userPwd.equals("123"))){
                chatView = new ChatView(userName);
                //建立服务器连接
                try{
                    InetAddress addr = InetAddress.getByName(null);//获取主机地址
                    mySocket = new Socket(addr,8081);//客户端套接字
                    loginJFrame.setVisible(false);
                    out = new PrintWriter(mySocket.getOutputStream());//输出流
                    out.println(simpleDateFormat.format(new Date()) + "用户[" + userName + "]已接入服务器");
                    out.flush();//清理缓冲区out数据
                }catch (IOException e){
                    e.printStackTrace();
                }

                ClientReadAndPrint readAndPrint = new ClientReadAndPrint();//新建文字读写线程
                readAndPrint.start();//启动线程


            }
            else{
                JOptionPane.showMessageDialog(loginJFrame,"账号或密码错误，请检查","提示",JOptionPane.WARNING_MESSAGE);
            }
        }
    }


    /*----------聊天界面监听--------------*/
    class ChatViewListen implements ActionListener{
        public void setJTextField(JTextField text){
            textInput = text;
        }
        public void setJTextArea(JTextArea textArea){
            textShow = textArea;
        }
        public void setChatViewJf(JFrame jFrame){
            chatViewJFrame = jFrame;

            //关闭聊天界面监听
            chatViewJFrame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    out.println(simpleDateFormat.format(new Date()) + "用户[" + userName + "]已从服务器断开");
                    out.flush();
                    System.exit(0);
                }
            });
        }


        //监听执行函数
        public void actionPerformed(ActionEvent event){
            try {
                JButton jbTemp = (JButton) event.getSource();
                String str = textInput.getText();
                if (jbTemp == xuan) {
                    str += "@xuan";
                }
                if (jbTemp == tao) {
                    str += "@tao";
                }
                if (jbTemp == yuan) {
                    str += "@yuan";
                }
                //if (jbTemp == send) {
                    //文本框为空情况
                    if ("".equals(str)) {
                        textInput.grabFocus();//焦点
                        JOptionPane.showMessageDialog(chatViewJFrame, "无法发送空字符串，请输入字符串！", "提示", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    out.println(userName + ":" + str);//输出给服务器
                    out.flush();

                    textInput.setText("");
                    textInput.grabFocus();
                //}

            }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
